package com.onesports.intelligent.k12.polarlight.service.wx;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onesports.framework.kit.common.util.ParamUtils;
import com.onesports.intelligent.k12.polarlight.common.errors.exceptions.BusinessException;
import com.onesports.intelligent.k12.polarlight.domain.dto.wx.CoachApplyDTO;
import com.onesports.intelligent.k12.polarlight.domain.entity.market.Message;
import com.onesports.intelligent.k12.polarlight.domain.entity.market.MessageNotify;
import com.onesports.intelligent.k12.polarlight.domain.entity.organization.OrganizationCampus;
import com.onesports.intelligent.k12.polarlight.domain.entity.wx.CoachApply;
import com.onesports.intelligent.k12.polarlight.domain.vo.wx.CoachApplyVO;
import com.onesports.intelligent.k12.polarlight.enums.MessageTypeEnum;
import com.onesports.intelligent.k12.polarlight.mapper.market.MessageMapper;
import com.onesports.intelligent.k12.polarlight.mapper.market.MessageNotifyMapper;
import com.onesports.intelligent.k12.polarlight.mapper.organization.OrganizationCampusMapper;
import com.onesports.intelligent.k12.polarlight.mapper.wx.CoachApplyMapper;
import com.onesports.intelligent.k12.polarlight.util.BeanCopyUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangcx
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class CoachApplyService extends ServiceImpl<CoachApplyMapper, CoachApply> {

    private final CoachApplyMapper mapper;
    private final MessageNotifyMapper messageNotifyMapper;
    private final MessageMapper messageMapper;
    private final OrganizationCampusMapper organizationCampusMapper;

    /**
     * 小程序端申请成为教练
     *
     * @param dto 入参
     */
    @Transactional(rollbackFor = Exception.class)
    public void apply(CoachApplyDTO dto) {
        Instant now = Instant.now();
        CoachApply entity = new CoachApply();
        BeanCopyUtil.copyProperties(dto, entity);
        entity.setApplyTime(now);
        this.mapper.insert(entity);
        // 校区id转为校区名称
        String campusNames = organizationCampusMapper.selectList(new LambdaQueryWrapper<OrganizationCampus>()
                        .eq(OrganizationCampus::getDeleted, false)
                        .in(OrganizationCampus::getId, Arrays.asList(dto.getCampusId()))).stream()
                .map(OrganizationCampus::getCampusName).collect(Collectors.toList()).toString();
        // 获取教练性别和年龄
        LocalDateTime localDate = LocalDateTime.now();
        int birthday = Integer.parseInt(dto.getIdCard().substring(6, 10));
        int age = localDate.getYear() - birthday;
        String gender = Integer.parseInt(dto.getIdCard().substring(16, 17)) % 2 == 0 ? "女" : "男";

        // 添加到消息表
        Message message = new Message();
        message.setTitle(MessageTypeEnum.COACH_APPLY.getDesc());
        message.setMsgType(MessageTypeEnum.COACH_APPLY.getValue());
        message.setContent(dto.getApplyName() + "("
                + gender + "，" + age + "岁，" + dto.getApplyPhone() + "，"
                + dto.getIdCard() + ")，服务社区：" + campusNames);
        message.setReceiverType(MessageTypeEnum.RECEIVER_TYPE_OP.getValue());
        messageMapper.insert(message);
        // 添加到消息通知表
        MessageNotify messageNotify = new MessageNotify();
        messageNotify.setMessageId(message.getId());
        messageNotify.setSendTime(Date.from(now));
        this.messageNotifyMapper.insert(messageNotify);

    }

    /**
     * function: 获取教练的申请信息
     *
     * @param wxUserId 微信UserId
     * @return CoachApplyVO 教练申请VO
     * @author WangCX
     * @since 2022/7/24 10:04
     */
    public List<CoachApplyVO> getApply(String wxUserId) {
        List<CoachApplyVO> applies = this.mapper.getApply(wxUserId);
        if (ParamUtils.isNotEmpty(applies)){
            for (CoachApplyVO apply : applies) {
                List<String> campusNames = new ArrayList<>();
                for (String s : apply.getCampusId()) {
                    OrganizationCampus organizationCampus = this.organizationCampusMapper.selectOne(
                            new LambdaQueryWrapper<OrganizationCampus>()
                                    .eq(OrganizationCampus::getId, s));
                    String campusName =ParamUtils.isNotEmpty(organizationCampus)?organizationCampus.getCampusName():null;
                    campusNames.add(campusName);
                }
                apply.setCampusNames(campusNames);
            }
        }
        return applies;
    }
}
